<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片布局 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 步骤条组件 -->
      <!-- align-center(居中效果) -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <!-- tab栏区域:el-tab-pane必须是el-tabs的子节点 -->
      <!-- 表单：label-position="top"(设置label在文本框上方) -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- before-leave 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="handleBeforeLeave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 选择商品分类的级联选择框 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="handleCascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 循环渲染动态参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <!-- 使用数组渲染复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="subItem"
                  v-for="(subItem, subIndex) in item.attr_vals"
                  :key="subIndex"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 循环生成静态属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片上传
                action:指定图片上传api接口
                :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
                :on-remove : 当用户点击图片右上角的X号时触发执行
                :on-success：当用户点击上传图片并成功上传时触发
                list-type ：设置预览图片的方式
                :headers ：设置上传图片的请求头 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
      <img :src="previewUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
// 官方推荐将lodash导入为_
import _ from 'lodash'

export default {
  data () {
    return {
      activeIndex: 0,
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        // 图片的数组
        pics: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }

        ]
      },
      // 获取商品分类的列表
      cateList: [],
      // 动态参数列表的数据
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 上传图片的URL地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传的 headers 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 保存预览图片的url地址
      previewUrl: '',
      // 控制图片预览对话框的显示与隐藏
      previewDialogVisible: false,
      // 商品的详情描述
      goods_introduce: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    // 级联选中器选中项变化 会触发这个函数
    handleCascaderChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 阻止 tab 栏的切换行为
    // activeName 将要去往的页面的 name
    // oldActiveName 从哪个页面出来
    handleBeforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        return false
      }
    },
    // 当用户点击 切换 tab 栏是触发
    async handleTabClick () {
      if (this.activeIndex === '1') {
        // 发送请求获取动态参数
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: 'many' } })
        res.data.forEach(t => {
          t.attr_vals = t.attr_vals.length === 0 ? [] : t.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        // 发送请求获取静态属性
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: 'only' } })
        this.onlyTableData = res.data
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 处理移除图片的操作
    handleRemove (file) {
      const tmpPath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(t => t.pic === tmpPath)
      this.addForm.pics.splice(index, 1)
    },
    // 监听图片上传成功事件
    handleSuccess (response) {
      // 图片上传成功后 将 response 里图片的临时路径保存在pics中
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 添加商品
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message({
            message: '请填写必要的表单项',
            type: 'error'
          })
        }
        // 将addForm进行深拷贝，避免goods_cat数组转换字符串之后导致级联选择器报错
        const formData = _.cloneDeep(this.addForm)
        // 将goods_cat从数组转换为"1,2,3"字符串形式
        formData.goods_cat = formData.goods_cat.join(',')
        formData.attrs = []
        // 处理动态参数
        this.manyTableData.forEach(t => {
          formData.attrs.push({
            attr_id: t.attr_id,
            attr_value: t.attr_vals.join(' ')
          })
        })
        // 处理静态属性
        this.onlyTableData.forEach(t => {
          formData.attrs.push({
            attr_id: t.attr_id,
            attr_value: t.attr_vals
          })
        })

        // 发送请求完成商品的添加
        const { data: res } = await this.$http.post('goods', formData)
        if (res.meta.status === 201) {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.$router.push('/goods')
        } else {
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        }
      })
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  }

}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px !important;
}
.btnAdd {
  margin-top: 10px;
}
</style>
